package com.collect.zambia.zhiUtils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import com.collect.zambia.MyApplication;

/**
 * Toast要全局定义统一的一个对象，避免出现Toast无法销毁的情况
 */

public class ToastUtil {

    private static Toast mToast;
    private static Context app;

    public static void init(Context app) {
        ToastUtil.app = app;
        initToast();
    }

    public static void s(String msg) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                @Override
                public void run() {
                    if (mToast == null){
                        if (app == null){
                            return;
                        }

                        initToast();
                    }

                    mToast.setDuration(Toast.LENGTH_SHORT);
                    mToast.setText(msg);
                    mToast.show();
                }
            });
        } else {
            if (mToast == null){
                if (app == null){
                    return;
                }

                initToast();
            }

            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.setText(msg);
            mToast.show();
        }
    }

    public static void l(String msg) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
                @Override
                public void run() {

                    if (mToast == null){
                        if (app == null){
                            return;
                        }
                        initToast();
                    }

                    mToast.setDuration(Toast.LENGTH_LONG);
                    mToast.setText(msg);
                    mToast.show();
                }
            });
        } else {

            if (mToast == null){
                if (app == null){
                    return;
                }
                initToast();
            }

            mToast.setDuration(Toast.LENGTH_LONG);
            mToast.setText(msg);
            mToast.show();
        }
    }

    private static void initToast(){
        int height = DisplayUtil.getAppHeight(MyApplication.getAppContext());

        mToast = Toast.makeText(app, "", Toast.LENGTH_LONG);
        mToast.setGravity(Gravity.TOP, 0, height*3 / 4);
    }



}
